/**
 * Copyright (c) 2016- https://github.com/beiyoufx
 *
 * Licensed under the Apache Licence 2.0
 */
package com.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 基础controller
 * 目前主要是输出返回
 * 可以扩展
 *
 * @author chuanxi.zhao
 */
public class BaseController {

    /**
     * 返回JSON数据
     *
     * @param response response返回
     * @param json     String类型的JSON数据
     * @throws java.io.IOException 读写异常
     */
    protected void writeJSON(HttpServletResponse response, String json) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.getWriter().write(json);
    }

    /**
     * 返回JSON数据
     *
     * @param response response返回
     * @param obj      Object类型的JSON数据
     * @throws java.io.IOException 读写异常
     */
    protected void writeJSON(HttpServletResponse response, Object obj) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("", "");
        response.setHeader("", "");
        response.getWriter().write(JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue));
    }
}
